package marchsoft.modules.four.h5.controller;

import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaModel;
import com.aliyun.teaopenapi.models.Config;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import marchsoft.annotation.AnonymousAccess;
import marchsoft.config.bean.RsaProperties;
import marchsoft.exception.BadRequestException;
import marchsoft.modules.four.h5.entity.vo.PhoneVo;
import marchsoft.modules.four.h5.entity.vo.UpdatePhoneVo;
import marchsoft.modules.four.h5.entity.vo.UserPassVo;
import marchsoft.modules.four.h5.service.SettingService;
import marchsoft.response.Result;
import marchsoft.utils.RedisUtils;
import marchsoft.utils.RsaUtils;
import marchsoft.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Random;

@RestController
@RequestMapping("/api/h5")
@Api(tags = "设置界面功能模块")
public class SettingController {

    public String CodeNum;
    private final RedisUtils redisUtils;
    private final PasswordEncoder passwordEncoder;

    @Autowired
    private SettingService settingService;

    public SettingController(RedisUtils redisUtils, PasswordEncoder passwordEncoder) {
        this.redisUtils = redisUtils;
        this.passwordEncoder = passwordEncoder;
    }

    @PostMapping("/updatePassword")
    @AnonymousAccess
    @ResponseBody
    @ApiOperation(value = "修改密码接口" ,notes = "author:xjm")
    public Result<Void> updatePassword(@RequestBody UserPassVo passVo, HttpServletRequest request) throws Exception {
        try {
            String oldPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, passVo.getOldPass());
            String newPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, passVo.getNewPass());
            long id = SecurityUtils.getCurrentUserId();
            String password = settingService.selectPassById(id);
            System.out.println(password);
            if (!passwordEncoder.matches(oldPass,password)){
                throw new BadRequestException("【修改密码失败】修改失败，旧密码错误");
            }
            if (passwordEncoder.matches(newPass, password)){
                throw new BadRequestException("【修改密码失败】新密码不能与旧密码相同");
            }
            String newPassword = passwordEncoder.encode(newPass);
            System.out.println(id);
            String idd= SecurityUtils.getCurrentUserId().toString();
            //清除redis缓存
            redisUtils.del("front::userId::"+id);
            settingService.updatePassword(newPassword,id);
        }catch (Exception e){
            throw new BadRequestException("【修改密码失败】" + e.getMessage());
        }
        return Result.success();
    }

    @PostMapping("/updatePhone")
    @AnonymousAccess
    @ResponseBody
    @ApiOperation(value = "修改手机接口" ,notes = "author:xjm")
    public Result<Void> updatePhone(@RequestBody UpdatePhoneVo updatePhoneVo, HttpServletRequest request) throws Exception {
        try {
            String oldPhone = updatePhoneVo.getOldPhone();
            String newPhone = updatePhoneVo.getNewPhone();
            String phoneCode = updatePhoneVo.getPhoneCode();
            long id = SecurityUtils.getCurrentUserId();
            String phone = settingService.selectPhoneById(id);
            if (!phoneCode.equals(CodeNum)){
                throw new BadRequestException("【修改手机号失败】修改失败，验证码错误");
            }
            if (!phone.equals(oldPhone)){
                throw new BadRequestException("【修改手机号失败】修改失败，旧手机号错误");
            }
            if (oldPhone.equals(newPhone)){
                throw new BadRequestException("【修改手机号失败】新手机号不能与旧手机号相同");
            }
            settingService.updatePhone(newPhone,id);
        }catch (Exception e){
            throw new BadRequestException("【修改密码失败】" + e.getMessage());
        }
        return Result.success();
    }

    @PostMapping("/getCode")
    @AnonymousAccess
    @ResponseBody
    @ApiOperation(value = "发送验证码" ,notes = "author:xjm")
    public Result<Void> getCode(@RequestBody PhoneVo phoneVo, HttpServletRequest request , HttpServletResponse response) throws Exception {
        try {
            String phoneNumber = phoneVo.getOldPhone();
            long id = SecurityUtils.getCurrentUserId();
            String oldPhone = settingService.selectPhoneById(id);
            if (!phoneNumber.equals(oldPhone)){
                return Result.error("【发送验证码失败】修改失败，旧手机号错误");
            }
            Random r = new Random();
            String number = "";
            for (int i =0;i<4;i++) {
                int n = r.nextInt(10);
                number=number+n;
            }
            com.aliyun.dysmsapi20170525.Client client = SettingController.createClient("LTAI5t61c89RHHqavHpcxEwr", "P432fBx4czIHOkzOkON2zXx3gYDmCY");
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setSignName("阿里云短信测试")
                    .setTemplateCode("SMS_154950909")
                    .setPhoneNumbers(phoneNumber)
                    .setTemplateParam("{\"code\":\""+number+"\"}");
            SendSmsResponse resp = client.sendSms(sendSmsRequest);
            com.aliyun.teaconsole.Client.log(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(resp)));
            CodeNum=number;
        }catch (Exception e){
            System.out.println(e);
        }
        return Result.success();
    }

    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    @PostMapping("/updateAvatar")
    @AnonymousAccess
//    @ResponseBody
    @ApiOperation(value ="更新头像",notes = "author : xjm")
    public Result<Void> updateAvatar(@RequestBody String path){
        String avatarPath = path.replace("\"","");
        System.out.println("修改头像接口");
        long id = SecurityUtils.getCurrentUserId();
        settingService.updateAvatar(id,avatarPath);
        redisUtils.del("front::userId::"+id);
        return Result.success();
    }
}
